package com.imageim.yimirror.ui.fragment;

import android.content.ClipData;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.DragEvent;
import android.view.HapticFeedbackConstants;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.imageim.yimirror.R;
import com.imageim.yimirror.base.BaseFragment;
import com.imageim.yimirror.base.Constants;
import com.imageim.yimirror.bean.imageManage.ComparePhotoBean;
import com.imageim.yimirror.bean.imageManage.ImagePhoto;
import com.imageim.yimirror.common.event.EventCode;
import com.imageim.yimirror.common.event.EventMessage;
import com.imageim.yimirror.common.network.NetUtil;
import com.imageim.yimirror.common.network.constants.NetConstants;
import com.imageim.yimirror.common.network.listener.NetCallback;
import com.imageim.yimirror.common.network.tool.ParamCreator;
import com.imageim.yimirror.common.ui.DraggablePhotoContainer;
import com.imageim.yimirror.common.ui.GlideUtils;
import com.imageim.yimirror.common.ui.SceneManager;
import com.imageim.yimirror.common.ui.tip.TipUtil;
import com.imageim.yimirror.common.util.AppUtil;
import com.imageim.yimirror.common.util.LogUtil;
import com.imageim.yimirror.common.util.ToastUtil;
import com.imageim.yimirror.common.util.UserUtil;
import com.imageim.yimirror.ui.activity.TakeMomeryPhotoActivity;
import com.imageim.yimirror.ui.adapter.DailyPhotoViewAdapter;
import com.martin.ads.omoshiroilib.util.BitmapUtils;

import org.apache.http.message.BasicNameValuePair;

import java.text.MessageFormat;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Yuaihen.
 * on 2018/7/6
 * 形象日记Fragment
 */
public class ImagePhotoFragment extends BaseFragment implements View.OnDragListener {
    private static final String TAG = "ImagePhotoFragment";
    @BindView(R.id.btn_addUserPhoto)
    Button mBtnAddUserPhoto;
    @BindView(R.id.iv_photo)
    ImageView mIvPhoto;
    @BindView(R.id.rv_photo_list)
    RecyclerView mRvPhotoList;
    @BindView(R.id.tv_tip)
    TextView mTvTip;
    @BindView(R.id.tv_close)
    TextView mTvClose;
    @BindView(R.id.panel_empty)
    LinearLayout mPanelEmpty;
    @BindView(R.id.tv_imageVersion)
    TextView mTvImageVersion;
    @BindView(R.id.draggable_container)
    DraggablePhotoContainer draggableContainer;
    @BindView(R.id.iv_photo2)
    ImageView mIvPhoto2;
    @BindView(R.id.btn_recompare)
    Button btnRecompare;
    @BindView(R.id.btn_ask)
    Button btnAsk;
    @BindView(R.id.iv_share_qrcode)
    ImageView ivShareQrcode;
    @BindView(R.id.tv_score1)
    TextView tvScore1;
    @BindView(R.id.tv_score2)
    TextView tvScore2;
    @BindView(R.id.tv_compare_tip)
    TextView tvCompareTip;
    @BindView(R.id.panel_qrcode)
    FrameLayout panelQrcode;

    private DailyPhotoViewAdapter mAdapter;
    private List<ImagePhoto.ClothingResultBean> mClothingResult;
    private String mCurrentOccasionIds;
    private static final int MSG_REFRESH_PHOTO_INFO = 201;
    private int dragPosition;
    private String photoNo1;
    private String photoNo2;
    private boolean[] canSetPhoto = {true, true};
    private ImageView[] imagePhoto;
    private boolean canDelete = true;

    @Override
    protected int getLayoutId() {
        return R.layout.image_photo_fragment;
    }

    @Override
    protected void initListener() {
        imagePhoto = new ImageView[]{mIvPhoto, mIvPhoto2};

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRvPhotoList.setLayoutManager(linearLayoutManager);
        mAdapter = new DailyPhotoViewAdapter(getContext(), mClothingResult);
        mRvPhotoList.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new DailyPhotoViewAdapter.OnItemClickListener() {
            @Override
            public void onClickPhoto(int position, String photoNo, boolean isCheck) {
                setItemDataToMainPage(position, photoNo, isCheck);
            }

            @Override
            public void onClickDelete(int position) {
                if (position < mClothingResult.size()) {
                    if (canDelete) {
                        deleteImagePhoto(position, mClothingResult.get(position).getPhotoNo());
                    }
                }
            }

            @Override
            public void onLongClickPhoto(ImageView imageView, int position) {
                dragPosition = position;
                Intent intent = new Intent();
                ClipData clipData = ClipData.newIntent("label", intent);
                View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(imageView);
                imageView.startDrag(clipData, shadowBuilder, imageView, 0);
                //震动反馈
                imageView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
            }
        });

        mIvPhoto.setOnDragListener(this);
        mIvPhoto2.setOnDragListener(this);
    }

    @Override
    public boolean onDrag(View view, DragEvent event) {
        //获取事件
        int action = event.getAction();
        switch (action) {
            case DragEvent.ACTION_DROP:
                LogUtil.d(TAG, "释放拖拽的view");
                GlideUtils.display(((ImageView) view), mClothingResult.get(dragPosition).getUrl());
                if (view == mIvPhoto) {
                    if (mAdapter != null) {
                        mAdapter.unCheckItemAndNotify(photoNo1);
                        photoNo1 = mClothingResult.get(dragPosition).getPhotoNo();
                        mAdapter.setSelectItem(photoNo1);
                        canSetPhoto[0] = false;
                    }
                } else if (view == mIvPhoto2) {
                    if (mAdapter != null) {
                        mAdapter.unCheckItemAndNotify(photoNo2);
                        photoNo2 = mClothingResult.get(dragPosition).getPhotoNo();
                        mAdapter.setSelectItem(photoNo2);
                        canSetPhoto[1] = false;
                    }
                }
                if (!TextUtils.isEmpty(photoNo1) && !TextUtils.isEmpty(photoNo2)) {
                    comparePhoto();
                }
                break;
            default:
        }
        return true;
    }


    @Override
    protected void initData() {
        //        myHandler = new MyHandler(this);
        panelQrcode.setVisibility(View.GONE);
        tvCompareTip.setVisibility(View.GONE);
        mTvImageVersion.setText(MessageFormat.format("形象力时尚AI {0}版", AppUtil.getVersionName(mContext)));
        getImagePhoto(false);
    }

    @Override
    public void onEventMainThread(EventMessage event) {
        switch (event.getCode()) {
            case EventCode.CODE_UPDATE_DAILY_PHOTO_LIST: // 刷新相册
                getImagePhoto(true);
                break;
            default:
        }
    }

    /**
     * 删除用户形象照片
     *
     * @param position item位置
     * @param photoNo  图片编号
     */
    private void deleteImagePhoto(final int position, String photoNo) {
        List<BasicNameValuePair> params = new ParamCreator()
                .add(Constants.PHOTO_NO, photoNo)
                .build();
        NetUtil.postObject(mContext, NetConstants.URL.DELETE_IMAGE_PHOTO, params, new NetCallback<String>() {

            @Override
            public void onStart() {
                canDelete = false;
            }

            @Override
            public void onSuccess(String result) {
                canDelete = true;
                mAdapter.unCheckItemAndNotify(photoNo);
                mClothingResult.remove(position);
                mAdapter.notifyItemRemoved(position);
                mAdapter.notifyItemRangeChanged(0, mClothingResult.size());
                if (mAdapter.getItemCount() == 0) {
                    showNullArea();
                }

                //取消选中
                if (photoNo.equals(photoNo1)) {
                    uncheckItem(0);
                } else if (photoNo.equals(photoNo2)) {
                    uncheckItem(1);
                }
            }


            @Override
            public void onFail(int errorCode, String errorMsg) {
                canDelete = true;
                TipUtil.show(errorMsg + errorCode);
            }
        });
    }


    /**
     * 点击item 设置数据到主界面
     *
     * @param position 点击item的位置
     * @param isCheck
     */
    private void setItemDataToMainPage(int position, String photoNo, boolean isCheck) {

        if (isCheck) {
            //选中
            for (int i = 0; i < canSetPhoto.length; i++) {
                if (canSetPhoto[i]) {
                    GlideUtils.display(imagePhoto[i], mClothingResult.get(position).getUrl());
                    if (i == 0) {
                        photoNo1 = mClothingResult.get(position).getPhotoNo();
                    } else {
                        photoNo2 = mClothingResult.get(position).getPhotoNo();
                    }
                    canSetPhoto[i] = false;
                    break;
                }
            }

            if (!TextUtils.isEmpty(photoNo1) && !TextUtils.isEmpty(photoNo2)) {
                comparePhoto();
            }
        } else {
            //取消选中
            if (photoNo.equals(photoNo1)) {
                uncheckItem(0);
            } else if (photoNo.equals(photoNo2)) {
                uncheckItem(1);
            }
        }


    }

    private void uncheckItem(int position) {
        if (position == 0) {
            mIvPhoto.setImageResource(R.drawable.ic_image_photo_example2);
            photoNo1 = null;
            tvScore1.setText("0%");
            canSetPhoto[0] = true;
        } else {
            mIvPhoto2.setImageResource(R.drawable.ic_image_photo_example2);
            photoNo2 = null;
            tvScore2.setText("0%");
            canSetPhoto[1] = true;
        }

        panelQrcode.setVisibility(View.GONE);
        tvCompareTip.setVisibility(View.GONE);
    }


    /**
     * 获取形象相册
     */
    private void getImagePhoto(final boolean isRefresh) {
        List<BasicNameValuePair> params = new ParamCreator()
                .add(Constants.PHOTO_NO, UserUtil.getPhotoNo())
                .build();
        NetUtil.getObject(mContext, NetConstants.URL.GET_IMAGE_PHOTO, params, new NetCallback<ImagePhoto>() {

            @Override
            public void onStart() {
                hideNullArea();
            }

            @Override
            public void onSuccess(ImagePhoto result) {

                if (result != null) {
                    setPhotoRecordResult(result);
                    if (isRefresh) {
                        if (mAdapter != null) {
                            mAdapter.checkItemAndNotify();
                        }
                        //                        sendRefreshMsg(result.getCurrentPhotoNo());
                    }
                } else {
                    showNullArea();
                }
            }


            @Override
            public void onFail(int errorCode, String errorMsg) {
                TipUtil.show(errorMsg + errorCode);
                showNullArea();
            }
        }, ImagePhoto.class);
    }


    /**
     * 设置形象相册数据
     *
     * @param result 返回bean
     */
    private void setPhotoRecordResult(ImagePhoto result) {
        if (result.getClothingResult() != null && result.getClothingResult().size() > 0) {
            mClothingResult = result.getClothingResult();
            mAdapter.setData(mClothingResult);
        } else {
            //没有拍过形象日记照片  显示拍照界面。。。这个注释写的不对
            showNullArea();
        }
    }


    /**
     * 跳转拍照界面
     */
    private void gotoTakePhoto() {
        Bundle data = new Bundle();
        data.putInt(Constants.TO_DO_FLAG, Constants.Action.UPLOAD_DAILY_PHOTO_RECORD);
        SceneManager.toScene(getContext(), TakeMomeryPhotoActivity.class, data);
    }


    @OnClick({R.id.btn_addUserPhoto, R.id.tv_close, R.id.btn_recompare, R.id.btn_ask, R.id.iv_photo, R.id.iv_photo2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_addUserPhoto:
                gotoTakePhoto();
                break;
            case R.id.tv_close:
                gotoTakePhoto();
                break;
            case R.id.btn_recompare:
                photoNo1 = null;
                photoNo2 = null;
                mIvPhoto.setImageResource(R.drawable.ic_image_photo_example2);
                mIvPhoto2.setImageResource(R.drawable.ic_image_photo_example2);
                tvScore1.setText("0%");
                tvScore2.setText("0%");
                panelQrcode.setVisibility(View.GONE);
                tvCompareTip.setVisibility(View.GONE);
                canSetPhoto[0] = true;
                canSetPhoto[1] = true;
                if (mAdapter != null) {
                    mAdapter.unCheckAllItemAndNotify();
                }
                //                ivShareQrcode.setImageBitmap(BitmapUtils.getQrcodeBitmap(result.getShowCompareUrl(), 190));
                break;
            case R.id.btn_ask:
                if (panelQrcode.getVisibility() == View.VISIBLE) {
                    panelQrcode.setVisibility(View.GONE);
                } else {
                    panelQrcode.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.iv_photo:
                mIvPhoto.setImageResource(R.drawable.ic_image_photo_example2);
                if (mAdapter != null) {
                    mAdapter.unCheckItemAndNotify(photoNo1);
                }
                tvScore1.setText("0%");
                panelQrcode.setVisibility(View.GONE);
                tvCompareTip.setVisibility(View.GONE);
                photoNo1 = null;
                canSetPhoto[0] = true;
                break;
            case R.id.iv_photo2:
                mIvPhoto2.setImageResource(R.drawable.ic_image_photo_example2);
                if (mAdapter != null) {
                    mAdapter.unCheckItemAndNotify(photoNo2);
                }
                tvScore2.setText("0%");
                panelQrcode.setVisibility(View.GONE);
                tvCompareTip.setVisibility(View.GONE);
                photoNo2 = null;
                canSetPhoto[1] = true;
                break;
            default:
        }
    }

    private void comparePhoto() {
        List<BasicNameValuePair> params = new ParamCreator().add("photoNo1", photoNo1)
                .add("photoNo2", photoNo2)
                .add("userId", UserUtil.getUserId()).build();
        NetUtil.postObject(mContext, NetConstants.URL.COMPARE_PHOTO, params, new NetCallback<ComparePhotoBean>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(ComparePhotoBean result) {
                tvScore1.setText(MessageFormat.format("{0}%", result.getScore1()));
                tvScore2.setText(MessageFormat.format("{0}%", result.getScore2()));
                panelQrcode.setVisibility(View.VISIBLE);
                tvCompareTip.setVisibility(View.VISIBLE);
                ivShareQrcode.setImageBitmap(BitmapUtils.getQrcodeBitmap(result.getShowCompareUrl(), 195, Color.RED));
                if (result.getScore1() > result.getScore2()) {
                    tvCompareTip.setText("图1的穿着看起来更适合您哦！");
                } else if (result.getScore1() < result.getScore2()) {
                    tvCompareTip.setText("图2的穿着看起来更适合您哦！");
                } else {
                    //                    int i = new Random().nextInt(2);
                    //                    if (i == 0) {
                    //                        tvCompareTip.setText(R.string.compare_same);
                    tvCompareTip.setText("图1和图2的着装度是一样的哦~");
                    //                    } else {
                    //                        tvCompareTip.setText(R.string.compare_same2);
                    //                    }
                }
            }

            @Override
            public void onFail(int errorCode, String errorMsg) {
                ToastUtil.show(errorMsg + errorCode);
            }
        }, ComparePhotoBean.class);
    }


    private void showNullArea() {
        if (mPanelEmpty != null) {
            mPanelEmpty.setVisibility(View.VISIBLE);
        }
    }

    private void hideNullArea() {
        if (mPanelEmpty != null) {
            mPanelEmpty.setVisibility(View.GONE);
        }
    }


}